package edu.iwyf.pms.service.impl;

import edu.iwyf.pms.dao.SysUserDao;
import edu.iwyf.pms.entity.SysUser;
import edu.iwyf.pms.service.SysUserService;
import edu.iwyf.pms.util.PassWordUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author 王永飞
 * 2021/12/21 15:42
 */
@Service
public class SysUserServiceImpl implements SysUserService {

    @Resource
    private SysUserDao dao;

    @Override
    public boolean addUser(SysUser sysUser) {
        //进行加盐
        sysUser.setSalt(PassWordUtil.creatSalt());
        //进行加密
        sysUser.setPassword(PassWordUtil.encryption(sysUser.getPassword(),sysUser.getSalt(),3));
        //查询用户是否存在
        SysUser sysUser1 = dao.selectByName(sysUser.getUsername());
        if (sysUser1!=null){
            return false;
        }
        int temp = dao.addUser(sysUser);
        if (temp > 0) {

            return true;
        }
        else
        return false;
    }
    //查询后再进行密码判断
//    @Override
//    public Map<String, Object> searchByNameAndPass(String username, String password) {
//        //1.准备容器
//        Map<String,Object> map = new HashMap<>();
//        //2.根据用户名进行查询
//        SysUser sysUser = dao.selectByName(username);
//        //3.进行判断
//        if (sysUser==null){
//            map.put("msg","用户名或密码错误");
//            map.put("code","700");
//        }
//        return map;
//    }

    //加密后再去数据库查询
    @Override
    public Map<String, Object> searchByNameAndPass(String username, String password) {
        //1.准备容器
        Map<String,Object> map = new HashMap<>();
        //2.对密码进行加密
        SysUser sysUser = dao.selectByName(username);
        if (sysUser==null){
            map.put("msg","用户名或密码错误");
            map.put("code","700");
        }
        password=PassWordUtil.encryption(password,sysUser.getSalt(),3);
        //3.进行查询
        sysUser=dao.selectByNameAndPass(username,password);
        if(sysUser==null){
            map.put("msg","用户名或密码错误");
            map.put("code","700");
        }else {
            map.put("msg","登录成功");
            map.put("data",sysUser);
            map.put("code",200);

        }
        return map;

    }
}
